const config_module = require('./config')
const Redis = require('ioredis')

//创建Redis客户端实例
const Rediscli = new Redis({
    host: config_module.redis_host,
    port: config_module.redis_port,
    // password: config_module.redis_passwd
});

/**
 * 监听错误消息
 */
Rediscli.on("error", function (err) {
    console.log("RedisCli connect error");
    Rediscli.quit();
})

/**
 * 根据key获取value
 * @param {*} key 
 * @returns 
 */
async function GetRedis(key) {
    try {
        const result = await Rediscli.get(key);
        if (result === null) {
            console.log('result:', '<' + result + '>', "This key cannot be find.");
            return null;
        }
        console.log('result:', '<' + result + '>', "Get key success!");
        return result;
    } catch (error) {
        console.log("GetRedis error is ", error);
        return null;
    }
}

/**
 * 根据key查询redis中是否存在key
 * @param {*} key 
 * @returns 
 */
async function QueryRedis(key) {
    try {
        const result = await Rediscli.exists(key);
        if (result === 0) {
            console.log('result:<', '<' + result + '>', "This key is null.");
            return null;
        }
        console.log('result:<', '<' + result + '>', "with this value!");
        return result;
    } catch (error) {
        console.log("QueryRedis error is ", error);
        return null;
    }
}

/**
 * 设置key和value，和过期时间
 * @param {*} key 
 * @param {*} value 
 * @param {*} exptime 
 * @returns 
 */
async function setRedisExpire(key, value, exptime) {
    try {
        await Rediscli.set(key, value)
        await Rediscli.expire(key, exptime);
        return true;
    } catch (error) {
        console.log("SetRedisExpire error is ", error);
        return false;
    }
}
/**
 * 退出函数
 */
function Quit() {
    Rediscli.quit()
}

module.exports = { GetRedis, QueryRedis, Quit, setRedisExpire }